<?php
//This file will be run on linux server as a standalone program/tool
//usage: php sdcv2file.php

//exec('whoami',$output, $status);
//var_dump($output);

//unset($output);
//exec('sdcv 习气',$output, $status);
//var_dump($output);

$inputFileName = "term_batch.txt";
$inputFile = file_get_contents($inputFileName);
$inputLines = explode("\n",$inputFile);
//"朗道英汉字典5.0"
$dics = array("Soothill-2003-by Longquan","Princeton 2014 Chinese-English by longquan","朗道汉英字典5.0","三藏法数","法相辞典","陈义孝佛学常见辞汇","FoGuangDaCiDian","佛学大辞典","WeiShiMingCiBaiHuaXinJie");
//$dics = array("法相辞典");
//$inputLines = array("缘起");

$fieldCount=3;
$idFieldIndex=1;
$chinese_key_field_index=2;
$batchFieldIndex=0;
foreach($inputLines as $inputLine){
	set_time_limit(0);
	$inputLine = trim($inputLine);
	if(empty($inputLine))
		continue;
	$fields = explode("|",$inputLine);
	if (count($fields)<>$fieldCount){
		echo "Count error\n";
		continue;
	}
	
	$id = sprintf("%08u",$fields[$idFieldIndex]);
	$chinese_key = trim($fields[$chinese_key_field_index]);
	//$chinese_key = iconv('UTF-8','GB2312',trim($fields[$chinese_key_field_index]));
	$batch = trim($fields[$batchFieldIndex]);
	
	//echo "$id|$chinese_key|$batch\r\n";

	//$chinese_key="习气";
	foreach($dics as $dic){
		unset($output);
		exec("sdcv -n -u \"$dic\" --utf8-output $chinese_key",$output, $status);
		$rets=dictExtract($dic,$chinese_key,$output);
		//var_dump($rets);
		//echo implode("[dd]",$rets);
		//exit;
		//echo "$chinese_key@$dic\n".implode("[dd]",$rets)."\n";
		if (empty($rets))
			echo "$chinese_key@$dic NOT found\n";
		else{
			echo "$chinese_key@$dic found\n";
			//$outputFileName = "output/$chinese_key@$dic.txt";
			$outputFileName = "output/$id@$dic.txt";
			file_put_contents($outputFileName,implode("[dd]",$rets));
		}
	}
}

function dictExtract($dic,$chinese_key,$output){
	//echo "I am here\n";
	$startFound=false;
	$rets = array();
	$dicLineBegin = "-->dic";
	$dicLineBeginLen = mb_strlen("-->dic");
	$chinese_key_line_begin = "-->".$chinese_key;
	$chinese_key_line_begin_len = mb_strlen($chinese_key_line_begin);
	//echo "chinese_key_line_begin_len=$chinese_key_line_begin_len\n";
	//var_dump($output);
	foreach($output as $k=>$line){
		if ($k==0)
			continue;
		$lineLength = mb_strlen(trim($line));
		//echo "$line\n lineLength=$lineLength\n";
		if($startFound){
			if (($lineLength>=$dicLineBeginLen) && (mb_substr($line,0,$dicLineBeginLen)==$dicLineBegin))
				$startFound=false;
			if (($lineLength>$chinese_key_line_begin_len) && (mb_substr($line,0,$chinese_key_line_begin_len)==$chinese_key_line_begin))
				$startFound=false;
			if (($startFound) && ($lineLength>0))
				$rets []= $line;
		}
		else{
			if (($lineLength==$chinese_key_line_begin_len) && (mb_substr($line,0,$chinese_key_line_begin_len)==$chinese_key_line_begin)){
				//echo "startFound!\n";
				$startFound=true;
			}
		}
	}
	return $rets;
}
exit;
?>